﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RPGXEngine.Networking
{
    public class NetworkMessage_ConnectToClient : NetworkMessage
    {
        #region Properties

        public int CurrentClientCount
        {
            get { return _currentClientCount; }
            set { _currentClientCount = value; }
        }
        private int _currentClientCount = 0;

        public override MessageTypes Type
        {
            get { return MessageTypes.ConnectToClient; }
        }

        public Int64 ClientAccountId
        {
            get { return _clientAccountId; }
            set { _clientAccountId = value; }
        }
        private Int64 _clientAccountId = 0;

        public string Handle
        {
            get { return _handle; }
            set { _handle = value; }
        }
        private string _handle = String.Empty;

        public int ModelIndex
        {
            get { return _modelIndex; }
            set { _modelIndex = value; }
        }
        private int _modelIndex = 0;

        #endregion

        public override int GetMessageSize()
        {
            int size = base.GetMessageSize();

            size += sizeof(int); // CurrentClientCount
            size += sizeof(Int64); // clientAccountId
            size += sizeof(int); // handle.length
            size += sizeof(char) * this.Handle.Length; // handle
            size += sizeof(int); // modelIndex

            return size;
        }

        public override byte[] GetMessageAsBytes()
        {
            List<byte> bytes = new List<byte>(base.GetMessageAsBytes());

            bytes.AddRange(BitConverter.GetBytes(this.CurrentClientCount));
            bytes.AddRange(BitConverter.GetBytes(this.ClientAccountId));

            bytes.AddRange(BitConverter.GetBytes(this.Handle.Length));
            foreach(char c in this.Handle)
                bytes.AddRange(BitConverter.GetBytes(c));

            bytes.AddRange(BitConverter.GetBytes(this.ModelIndex));

            return bytes.ToArray();
        }

        public override int FromBytes(byte[] bytes, int index)
        {
            index = base.FromBytes(bytes, index);

            this.CurrentClientCount = BitConverter.ToInt32(bytes, index);
            index += sizeof(int);

            this.ClientAccountId = BitConverter.ToInt64(bytes, index);
            index += sizeof(Int64);

            int handleLength = BitConverter.ToInt32(bytes, index);
            index += sizeof(int);

            for (int i = 0; i < handleLength; i++)
            {
                this.Handle += BitConverter.ToChar(bytes, index);
                index += sizeof(char);
            }

            this.ModelIndex = BitConverter.ToInt32(bytes, index);
            index += sizeof(int);

            return index;
        }
    }
}
